package exec;

/**
 * @Description 给定两个整数 a 和 b ，求它们的除法的商 a/b ，要求不得使用乘号 '*'、除号 '/' 以及求余符号 '%' 。
 * @Date 2022/10/25 10:16
 * @Created by wangjun
 */
public class Divide {

    public static void main(String[] args) {
        System.out.println(divide0(-2147483648, 2));
    }


    public static int divide(int a, int b) {
        if (a == Integer.MIN_VALUE && b == -1) {
            return Integer.MAX_VALUE;
        }
        if (a == b) {
            return 1;
        }
        if (a == 0) {
            return 0;
        }
        if (b == 1) {
            return a;
        }
        if (b == -1) {
            return -a;
        }
        boolean flag = (a < 0 && b > 0) || (a > 0 && b < 0);
        if (a > 0) {
            a = -a;
        }
        if (b > 0) {
            b = -b;
        }
        int result = 0;
        while (a <= b) {
            int base = b, count = 1;
            while (base < Integer.MAX_VALUE >> 1 && base + base >= a) {
                base <<= 1;
                count <<= 1;
            }
            a -= base;
            result += count;
        }
        return flag ? -result : result;
    }

    public static int divide0(int a, int b) {
        int min = Integer.MIN_VALUE, max = Integer.MAX_VALUE;
        if (a == min && b == -1) {
            return max;
        }
        if (a == b) {
            return 1;
        }
        if (a == 0) {
            return 0;
        }
        if (b == 1) {
            return a;
        }
        if (b == -1) {
            return -a;
        }
        boolean isPos = (a < 0 && b > 0) || (a > 0 && b < 0);
        if (a > 0) {
            a = -a;
        }
        if (b > 0) {
            b = -b;
        }
        int result = 0;
        while (a <= b) {
            int d = b, c = 1;
            while (d > min >> 1 && d + d >= a) {
                d <<= 1;
                c <<= 1;
            }
            a -= d;
            result += c;
        }
        return isPos ? -result : result;
    }

    /**
     * 功能描述: 初版，采用b累计法
     *
     * @Param: [a, b]
     * @Return: int
     */
    public static int divide1(int a, int b) {
        int MIN = Integer.MIN_VALUE, MAX = Integer.MAX_VALUE, MIN_LIMIT = MIN >> 1; // -1073741824
        if (a == MIN && b == -1) return MAX; // 特判
        if (a == 0 || b == 0) {
            return 0;
        }
        boolean isPos = (a < 0 && b > 0) || (a > 0 && b < 0);
        if (a < 0) {
            a = -a;
        }
        if (b < 0) {
            b = -b;
        }
        int count = 0;
        int sum = b;
        while (b < Integer.MAX_VALUE >> 1 && sum <= a) {
            sum += b;
            count++;
        }
        return isPos ? -count : count;
    }
}
